package ynu.edu.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.common.domain.PageDTO;
import ynu.edu.common.exception.DbException;
import ynu.edu.common.utils.BeanUtils;
import ynu.edu.common.utils.CollUtils;
import ynu.edu.common.utils.UserContext;
import ynu.edu.user.domain.dto.AddressDTO;
import ynu.edu.user.domain.po.Address;
import ynu.edu.user.domain.vo.AddressQuery;
import ynu.edu.user.mapper.AddressMapper;
import ynu.edu.user.service.IAddressService;

import java.time.LocalDateTime;
import java.util.List;


@Service
@RequiredArgsConstructor
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

    private final AddressMapper addressMapper;

    @Override
    public void createAddress(AddressDTO addressDTO) {
        //1.判断是否传入用户id
        if (addressDTO.getUserId() == null) {
            addressDTO.setUserId(UserContext.getUser());
        }
        // 2..判断是否是用户的第一个地址
        Integer count = query().eq("user_id", addressDTO.getUserId()).count();
        if (count == 0) {
            // 第一个地址，设置为默认地址
            addressDTO.setIsDefault(1);
        } else {
            addressDTO.setIsDefault(0);
        }

        if (addressDTO.getIsDefault() == 1) {
            // 如果是默认地址，则将当前用户的所有地址设置为非默认地址
            update().eq("user_id", addressDTO.getUserId())
                    .set("is_default", 0)
                    .update();
        }
        // 2.保存地址
        Address address = BeanUtil.copyProperties(addressDTO, Address.class);
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());
        save(address);
    }

    @Override
    public void updateAddress(Long id, AddressDTO addressDTO) {
        //1.判断是否存在该地址
        Address address = getById(id);
        if (address == null) {
            throw new DbException("地址不存在");
        }
        //2.修改地址
        address = BeanUtil.copyProperties(addressDTO, Address.class);
        address.setUpdateTime(LocalDateTime.now());
        updateById(address);
    }

    @Override
    public Address findAddressById(Long id) {
        //1.判断是否存在该地址
        Address address = getById(id);
        if (address == null) {
            throw new DbException("地址不存在");
        }
       return address;
    }

    @Override
    public List<Address> findMyAddresses() {
        // 1.查询列表
        Long userid = UserContext.getUser();
        if (userid == null){
            throw new DbException("用户未登录");
        }
        return query()
                .eq("user_id", userid)
                .list();
    }

    @Override
    public void setDefaultAddress(Long id) {
        //1.判断是否存在该地址
        Address address = getById(id);
        if (address == null) {
            throw new DbException("地址不存在");
        }
        //2.判断是否为默认地址
        if (address.getIsDefault() == 1) {
            throw new DbException("该地址已经是默认地址");
        }
        //3.修改默认地址
        // 3.1.把该用户的所有地址设置为非默认地址
        update().eq("user_id", UserContext.getUser())
                .set("is_default", 0)
                .update();
        // 3.2.修改当前地址为默认地址
        update().eq("id", id)
                .set("is_default", 1)
                .set("update_time", LocalDateTime.now())
                .update();
    }

    @Override
    public AddressDTO findDefaultAddress() {
        //判断该用户是否有地址
        Address address = query()
                .eq("user_id", UserContext.getUser())
                .eq("is_default", 1)
                .one();
        if (address == null) {
            throw new DbException("该用户没有默认地址");
        }
        return BeanUtil.copyProperties(address, AddressDTO.class);
    }

    @Override
    public PageDTO<Address> findAllAddresses(AddressQuery addressQuery) {
        try {
            //1.构造查询条件
            LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(StrUtil.isNotBlank(addressQuery.getCity()), Address::getCity, addressQuery.getCity())
                    .like(StrUtil.isNotBlank(addressQuery.getProvince()), Address::getProvince, addressQuery.getProvince())
                    .like(StrUtil.isNotBlank(addressQuery.getTown()), Address::getTown, addressQuery.getTown())
                    .like(StrUtil.isNotBlank(addressQuery.getStreet()), Address::getStreet, addressQuery.getStreet())
                    .like(StrUtil.isNotBlank(addressQuery.getContact()), Address::getContact, addressQuery.getContact())
                    .like(StrUtil.isNotBlank(addressQuery.getMobile()), Address::getMobile, addressQuery.getMobile())
                    .eq(addressQuery.getUserId() != null, Address::getUserId, addressQuery.getUserId())
                    .eq(addressQuery.getIsDefault() != null, Address::getIsDefault, addressQuery.getIsDefault());

            //2.分页查询
            Page<Address> addressPage = addressMapper.selectPage(addressQuery.toMpPageDefaultSortByCreateTimeDesc(), queryWrapper);
            return PageDTO.of(addressPage);
        }
        catch (Exception e) {
            throw new DbException("查询地址失败", e);
        }
    }

}
